package com.hundsun.hsOffer.model;

import com.hundsun.hsOffer.common.Constant;
import com.hundsun.hsOffer.dto.UserDto;
import com.hundsun.hsOffer.model.base.BaseSysUsers;
import com.hundsun.hsOffer.utils.CryptographyUtil;
import com.hundsun.hsOffer.utils.DataGrid;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Authentication;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class SysUsers extends BaseSysUsers<SysUsers> {
	private Logger logger = Logger.getLogger(SysUsers.class);
	public static final SysUsers dao = new SysUsers();

	public SysUsers findByUserNameAndPassword(String username, String password) {
		String sql = "select * from sys_users u where u.username = ? and u.password = ?";
		return dao.findFirst(sql, username,
				CryptographyUtil.md5(password, Constant.SALT));
	}

	public DataGrid<UserDto> findByPage(Integer page, Integer rows) {
		String select = "select * ";
		String sqlExcepteSelect = "from sys_users";
		Page<SysUsers> paginate =  dao.paginate(page, rows, select, sqlExcepteSelect);
		List<UserDto> userDtoList = new ArrayList<UserDto>();
		for(SysUsers sysUsers :paginate.getList()){
			UserDto userDto = new UserDto();
			try {
				BeanUtils.copyProperties(userDto,sysUsers);
				String roleSql = "select * from user_roles ur,sys_roles r where ur.userId = ? and ur.roleId = r.roleId";
				List<SysRoles> rolesList = SysRoles.dao.find(roleSql,sysUsers.getUserId());
				StringBuffer roleNames = new StringBuffer();
				for (SysRoles roles : rolesList){
					roleNames.append(roles.getRoleName() + "  ");
				}
				userDto.setUserRoles(roleNames.toString());
				userDtoList.add(userDto);
			} catch (IllegalAccessException e) {
				logger.error("sysUsers -> dto 转化异常",e);
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				logger.error("sysUsers -> dto 转化异常",e);
				e.printStackTrace();
			}
		}
		DataGrid<UserDto> dataGrid = new DataGrid<UserDto>();
		dataGrid.setTotal(paginate.getTotalRow());
		dataGrid.setRows(userDtoList);
		return dataGrid;
	}

	public boolean saveUser(SysUsers sysUser) {
		SysUsers user = dao.findByUserName(sysUser.getUsername());
		sysUser.setPassword(CryptographyUtil.md5(sysUser.getPassword(), Constant.SALT));
		return user== null ? sysUser.save() : false;
	}

	public SysUsers findByUserName(String username) {
		String sql = "select * from sys_users where username = ?";
		SysUsers user = dao.findFirst(sql,username);
		return user;
	}
}
